package com.eascs.admin.classify.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.admin.classify.entity.O2oLoanAbjustForm;
import com.eascs.admin.classify.entity.O2oLoanAbjustType;
import com.eascs.admin.classify.entity.O2oLoanAbjustTypeFlow;
import com.eascs.admin.classify.service.O2oClassifySerivce;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.dao.PageResult;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Controller
@RequestMapping("/classify")
public class O2oClassifyController extends BaseMasterViewController {

	@Autowired
	O2oClassifySerivce classifySerivce;

	@RequestMapping("/au")
	public String indexAu(O2oLoanAbjustForm abjustForm) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "AUTO_CLASSIFY");
		abjustForm.setPageSize(10);
		String o2ourl = "/classify/au";
		String reporto2ourl = "/classify/download";
		String loanType = abjustForm.getLoanType() == null ? "" : abjustForm.getLoanType();
		String provincialArea = abjustForm.getProvincialArea() == null ? "" : abjustForm.getProvincialArea();
		String opererName = abjustForm.getOpererName() == null ? "" : abjustForm.getOpererName();
		String operationPlatform = abjustForm.getOperationPlatform() == null ? "" : abjustForm.getOperationPlatform();
		String loanUser = abjustForm.getLoanUser() == null ? "" : abjustForm.getLoanUser();
		String billCode = abjustForm.getBillCode() == null ? "" : abjustForm.getBillCode();
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanType", loanType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "provincialArea", provincialArea);
		o2ourl = UrlUtil.appendUrl(o2ourl, "opererName", opererName);
		o2ourl = UrlUtil.appendUrl(o2ourl, "operationPlatform", operationPlatform);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanUser", loanUser);
		o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
		o2ourl = o2ourl + "&pageIndex=";
		String titles[] = { "贷款单号", "借款人", "信贷经理", "经营平台", "省区", "放款金额", "代偿总额", "代偿时间", "代偿回款总额", "逾期总额", "逾期时间",
				"贷款分类", "到期时间" };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, null, null, null, null,
				new SelectDataOption("CLASSIFY"), null };
		PageResult<Object[]> pageResult = classifySerivce.queryByPageAuto(abjustForm);
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFirstRenderColumnIndex(0);
		ViewContext.put("vo", abjustForm);
		ViewContext.put("o2oPagingInfo", o2oPagingInfo);
		ViewContext.put("reporto2ourl", reporto2ourl);
		return "classify/index_auto";
	}

	/**
	 * 贷款自动分类导出（已优化）
	 * @param abjustForm
	 * @param httpServletResponse
	 * @param request
	 */
	@RequestMapping("/download")
	public void dowanload(O2oLoanAbjustForm abjustForm, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		abjustForm.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = classifySerivce.queryByPageAuto(abjustForm, "download");
		try {
			String outfile = "贷款自动分类.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(),
					O2oClassifyController.class.getResourceAsStream("/excelTemplate/classify-au.xls"),
					defaultRowWriteHandler);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}
	}

	@RequestMapping("/ma")
	public String indexMa(O2oLoanAbjustForm abjustForm) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "MACOAL_CLASSIFY");
		abjustForm.setPageSize(10);
		String o2ourl = "/classify/ma";
		String loanType = abjustForm.getLoanType() == null ? "" : abjustForm.getLoanType();
		String operationPlatform = abjustForm.getOperationPlatform() == null ? "" : abjustForm.getOperationPlatform();
		String createUserName = abjustForm.getCreateUserName() == null ? "" : abjustForm.getCreateUserName();
		String flowStatus = abjustForm.getFlowStatus() == null ? "" : abjustForm.getFlowStatus();
		String createTimeStart = abjustForm.getCreateTimeStart() == null ? "" : abjustForm.getCreateTimeStart();
		String createTimeEnd = abjustForm.getCreateTimeEnd() == null ? "" : abjustForm.getCreateTimeEnd();
		String loanUser = abjustForm.getLoanUser() == null ? "" : abjustForm.getLoanUser();
		String billCode = abjustForm.getBillCode() == null ? "" : abjustForm.getBillCode();
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanType", loanType);
		o2ourl = UrlUtil.appendUrl(o2ourl, "operationPlatform", operationPlatform);
		o2ourl = UrlUtil.appendUrl(o2ourl, "createUserName", createUserName);
		o2ourl = UrlUtil.appendUrl(o2ourl, "flowStatus", flowStatus);
		o2ourl = UrlUtil.appendUrl(o2ourl, "createTimeStart", createTimeStart);
		o2ourl = UrlUtil.appendUrl(o2ourl, "createTimeEnd", createTimeEnd);
		o2ourl = UrlUtil.appendUrl(o2ourl, "loanUser", loanUser);
		o2ourl = UrlUtil.appendUrl(o2ourl, "billCode", billCode);
		o2ourl = o2ourl + "&pageIndex=";
		String titles[] = { "贷款单号", "借款人", "信贷经理", "经营平台", "省区", "原状态", "调整状态", "单据状态", "创建人", "创建时间" };
		Button titleButtons[] = { ButtonHelper.createAjaxButton(null, "/rclassify/detail?id=") };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("CLASSIFY"),
				new SelectDataOption("CLASSIFY"), new SelectDataOption("O2O_BILLSTATUS") };
		PageResult<Object[]> pageResult = classifySerivce.queryByPageMamuil(abjustForm);
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setTitleButtons(titleButtons);
		ViewContext.put("vo", abjustForm);
		ViewContext.put("o2oPagingInfo", o2oPagingInfo);
		return "classify/index_manoal";
	}

	@RequestMapping("/update_view")
	public String updateClassify() {
		return "classify/update_info";
	}

	@RequestMapping("/update_file")
	public String updateClassifyFile(O2oLoanAbjustType abjustType) {
		O2oLoanAbjustType loanAbjustType = classifySerivce.queryByLoanapplyNo(abjustType.getLoanapplyNo());
		O2oLoanAbjustTypeFlow abjustTypeFlow = classifySerivce.queryFlowCById(loanAbjustType.getId());
		User user = null;
		if (null == UserHolder.getUser()) {
			user = new User();
			user.setNo("1");
			user.setCname("系统管理员");
		} else {
			user = UserHolder.getUser();
		}
		if (null == abjustTypeFlow) {
			abjustTypeFlow = new O2oLoanAbjustTypeFlow();
			abjustTypeFlow.setNewLoanType(loanAbjustType.getNewLoanType());
			abjustTypeFlow.setOldLoanType(loanAbjustType.getOldLoanType());
			abjustTypeFlow.setAbjustId(loanAbjustType.getId());
			abjustTypeFlow.setCreateUserName(user.getCname());
			abjustTypeFlow.setCreateTime(new Date());
			abjustTypeFlow.setCreateUserNo(user.getNo());
			abjustTypeFlow.setIsDelete(StatusContexts.O2O_NO);
			abjustTypeFlow.setIsNew(StatusContexts.O2O_YES);
			abjustTypeFlow.setFlowStatus(StatusContexts.O2O_NEW);
			abjustTypeFlow.setAjustReason(abjustTypeFlow.getAjustReason());
			classifySerivce.insertFlow(abjustTypeFlow);
		} else if (!abjustTypeFlow.getFlowStatus().equals(StatusContexts.O2O_BANK_CLO)) {
			ViewContext.put("status", "clo");
		}

		ViewContext.put("entity", loanAbjustType);
		ViewContext.put("abjustTypeFlow", abjustTypeFlow);
		return "classify/update_file_info";
	}
}
